<template> 
  <div class="myPage" v-if="myUrl" :style="{with:frameStyle.width,height:frameStyle.height}">
      <div style="z-index: 99999;position: absolute; bottom: 100px;color: #dedede;margin: 0 auto;text-align: center;width: 100%;" v-if="!networkStatus" v-show="networkShow&&myUrl.indexOf('offline')<=0">
        <span style="margin-right: 20px;" @click="networkShow=!networkShow">网络状态：离线</span>
        <v-btn @click="reloadURL"  class="flex-grow-1" style="margin-right: 20px;"
        height="48"
        variant="tonal">重新加载</v-btn>
        <v-btn @click="reloadWin"  class="flex-grow-1"
        height="48" color="#5865f2"
        variant="tonal">重启</v-btn>
      </div> 
     <webview id="my-webview" nodeintegration="true" :src="myUrl" 
    :preload="path+'/webview/webview-preload.js'" frameborder="0"
    :width="frameStyle.width" :height="frameStyle.height"  v-if="path"/>
    <iframe  id="my-webview" style="vertical-align:bottom;"
     frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"  
     :src="myUrl" :width="frameStyle.width" :height="frameStyle.height"  v-else />
    <License /> 
  </div>
</template>

<script setup lang="ts">   


const networkStatus = ref(true)
const networkShow = ref(true)

let path="";
let projectTempPath="";
let projects=[];
let projectLocalIds=[]; 
if(window.electronAPI){ 
  path=window.electronAPI.base(); 
  getProjectPath(); 
  window.electronAPI.onWinChangeEvent((event, data)=>{
    console.log(data)
    console.log(event)
    resizeFrame(data)
  });
  window.electronAPI.getNetworkStatus((event, data)=>{ 
    if(!networkStatus.value&&data){
      proxy?.$Bus.emit('SystemInfoMsg', {msg:"网络已连接"});
      setTimeout(function(){
        proxy?.$Bus.emit('NetWorkReload', {});
        reloadWin();
      },1000) 
    }
    networkStatus.value=data;  
  })
}

function resizeFrame(data){
  let tt= data;
  if(tt.width<=900){
    tt.width=900;
  }

  if(tt.height<=800){
    tt.height=800;
  }
  // tt.height=tt.width/1920*1080

  frameStyle.value=tt; 
  myUrl.value=updateQueryStringParameter(myUrl.value,"t",new Date().getTime())
}

async function getProjectPath(){
  let tt= await window.electronAPI.getWinInfo();
  resizeFrame(tt)
  projectTempPath=await window.electronAPI.getLocalServer();
  // projectTempPath=projectTempPath+"\\Project";

  projects= await window.electronAPI.getLocalProject();
  if(!projectTempPath){
    projectTempPath="http://localhost:9999" 
  } 
  projects.forEach(item=>{
    item.type="offline"
    item.url=projectTempPath+"/offline.html#/chart/offline/"+item.id
    item.img=projectTempPath+item.img
    listData.value.push(item) 
   })
  
}
const myUrl =ref("")
const frameStyle =ref({})
import { getCurrentInstance,ref,reactive,defineProps,defineComponent,onMounted,computed} from "vue"; 
const {proxy} = getCurrentInstance();
import { useRouter } from 'vue-router'
import { useThemeStore } from '../stores/theme'
import { useLicenseStore } from '../stores/license'
import { useUserStore } from '../stores/user'
const router = useRouter()
const userStore = useUserStore()
const themeStore = useThemeStore()   
const licenseStore = useLicenseStore()    
const queryType=ref('');
const listData=ref([])
//获取数据
function getData(){
}
getData();
 
//下载离线版本 
const list=computed(()=>{
  return  listData.value.filter(item=>{
    if(queryType.value){
      if(item.type==queryType.value){
        return item
      }else{
        return false
      }
    }
    return item
  })
})
onMounted(() => { 
  // myUrl.value="http://183.221.0.153:35003/my/";
  // myUrl.value="http://localhost:3000/my/";
  if(!themeStore.themeUrl){
    themeStore.themeUrl="http://183.221.0.153:35003/my/"
    // themeStore.themeUrl="http://www.codeforest.cn/"
  }
  themeStore.themeUrl="http://183.221.0.153:35003/my/"
  // themeStore.themeUrl="http://11.18.1.67:3000/my/"
  // themeStore.themeUrl="http://www.codeforest.cn/"
  myUrl.value=themeStore.themeUrl
  // myUrl.value="http://183.221.0.153:35003/my/";
  bindWebView();
}); 
let myWebview;
function bindWebView(){  
  const webview = document.querySelector('webview');
  myWebview=webview;
  if(myWebview&&myUrl.value) {   
      try {
        webview.executeJavaScript(`window['agent']='${userStore.agent}'`) 
      } catch (error) {} 
      myWebview.addEventListener('dom-ready', initClientDataFun,false); 
  }
}
async function initClientDataFun(){
  try {
    const appInfo = await window.electronAPI.getAppInfo() 
    let obj = {agent:userStore.agent,appInfo:appInfo}
    myWebview.executeJavaScript(`initClientData(${JSON.stringify(obj)})`)  
  } catch (error) {}  
}
function updateQueryStringParameter(uri, key, value) {
    if(!value) { return uri }
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    }
    else {
        return uri + separator + key + "=" + value;
    }
}
proxy?.$Bus.off("ShowThemeWebURL",function(){});
proxy?.$Bus.on('ShowThemeWebURL', function(data){ 
  if(!data.url){
    return;
  }  
  let apiHost= "";
  if(userStore.apiHost){
    apiHost=userStore.apiHost;
  }   
  let myNewurl=updateQueryStringParameter(data.url,"agent",userStore.agent);
  if(data&&data.url&&data.url.indexOf("/")==0){ 
    myNewurl=apiHost+updateQueryStringParameter(data.url,"agent",userStore.agent);
  }
  if(myNewurl&&myNewurl==myUrl.value&&mySheet.value){
    return;
  }
  myUrl.value=myNewurl;  
  setTimeout(function(){
      bindWebView();
  },500); 
  //测试下网络情况
  setTimeout(function(){
    reloadNetworkData() 
  },3000);
})


function reloadNetworkData(){
   //在线的情况 
    window.electronAPI.checkNetwork({});   
}
function reloadURL(){ 
  reloadNetworkData()
  //在线的情况     
  if(networkStatus.value&&myUrl.value){
    setTimeout(function(){
      proxy?.$Bus.emit('ShowThemeWebURL',{url:myUrl.value});
    },2000); 
  }else{ 
    if(!networkStatus.value){
      proxy?.$Bus.emit('SystemInfoMsg', {msg:"请检查网络"});
    }  
  } 
}  

function reloadWin(){
  window.electronAPI.reloadWin({}); 
}
</script>

<style lang="scss" scoped>  
.myPage{
  .v-card-title{
    margin-top: 10px;
    font-size: 30px;
  }
  // min-height: 1080px;
  // height:1920px;
  // width: 1080px;
  // position: absolute;
  overflow: hidden;
}

</style>